package com.zmj.controller;

import com.zmj.common.ResponseVO;
import com.zmj.common.lock.RedissonLock;
import com.zmj.constant.Constants;
import com.zmj.exception.CustomizeException;
import com.zmj.exception.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 分布式锁演示
 */

@RestController
@RequestMapping("redisson/")
@Slf4j
public class RedissonController {

    @Autowired
    private RedissonLock redissonLock;

    @GetMapping("lock/{id}")
    public ResponseVO lock(@PathVariable(value = "id") String id) {
        String lockKey = Constants.RedisKeyPrefix.LOCK + id;
        boolean b = redissonLock.tryWatchDogLock(lockKey, TimeUnit.SECONDS, 1);
        if (!b) {
            throw new CustomizeException(ErrorCodeEnum.SYSTEM_RUNNING);
        }
        try {
            TimeUnit.SECONDS.sleep(10000);
            log.info("lockKey :[{}]获取锁,开始执行 ", lockKey);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            redissonLock.unlock(lockKey);
            log.info(" lockKey:[{}],finally unlock 成功", lockKey);
        }
        return ResponseVO.build();
    }
}
